<!-- 类编辑 -->
<template>
    <div>
        <el-dialog
        title="编辑分类"
        :visible.sync="centerDialogVisible"
        width="80%"
        @close="closeDialog">
        <div class="Main">
            <el-form :model="typeForm" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="分类名称">
                    <el-input v-model="typeForm.catName"></el-input>
                </el-form-item>
                <el-form-item label="分类说明" prop="memo">
                    <el-input type="textarea" v-model="typeForm.memo" :autosize="{minRows: 7}"></el-input>
                </el-form-item>
                <el-form-item prop="attr" lebel-position="right" class="custom-checkbox" >
                    <template>
                        <div class="content">
                        <el-checkbox v-model="isCheck"></el-checkbox>
                        <span>分类属性</span>
                        </div>
                    </template>
                    
                </el-form-item>
                <el-card shadow="never" body-style="{border:1px solid black}" v-show="isCheck == true" style="height: 300px;">
                <el-button type="primary" @click="addPrimary" class="addPrimary">+ 一级属性</el-button>
                <el-table 
                class="main-table"
                :data="inputForm"
                row-key="name"
                :row-style="{'height':'54px'}"
                lazy
                default-expand-all
                @cell-click="tabClick"
                @cell-mouse-enter="tabClick"
                @cell-mouse-leave="inputBlur"
                :row-class-name="tableRowClassName"
                :cell-class-name="tableCellClassName"
                :tree-props="{children: 'editDetailDTOS', hasChildren: 'editDetailDTOS'}"
                style="width: 100%;margin-top: 40px;">
                <el-table-column prop="name" label="属性名称" width="280" header-align="left"> 
                    <template slot-scope="scope">
                        <span :class="{'name-position':!scope.row.editDetailDTOS}">
                        <span v-if="scope.row.index === clickRow && scope.column.index === clickCell &&scope.row.isMe  " class="input-index">
                            <el-input
                            ref="editInput"
                            v-model="data_change"
                            maxlength="50"
                            size="mini"
                            @blur="inputBlur"
                            />
                        </span>
                        <span v-else>{{ scope.row.name }}
                            <span v-if="scope.row.parentFlag" class="ParentFlag">来源于父节点</span> 
                        </span>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="录入方式" class="input-mathode" width="200px">
                    <template slot-scope="scope" >
                        <el-select v-model="scope.row.inputType" placeholder="请选择" size="small" v-if="!scope.row.editDetailDTOS"  style="margin-bottom: 15px;">
                            <el-option v-for="item in option" :label="item.label" :value="item.value" :key="item.value"/>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="type" label="选取类型" width="240px">
                    <template slot-scope="scope">
                    <el-radio-group v-model="scope.row.selectType" v-if="!scope.row.editDetailDTOS||(scope.row.delFlag&&scope.row.attributeTypeId)">
                        <el-radio :label="0">唯一</el-radio>
                        <el-radio :label="1">单选</el-radio>
                        <el-radio :label="2">多选</el-radio>
                    </el-radio-group>
                    </template>
                </el-table-column>
                <el-table-column prop="canAdd" label="允许添加">
                    <template slot-scope="scope">
                        <span>
                        <el-switch v-model="scope.row.handAddStatus" active-color="#67c23a" :active-value="1"
                        :inactive-value="0" v-if="!scope.row.editDetailDTOS">
                        </el-switch>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="attribute" label="属性值">
                    <template slot-scope="scope">
                        <span v-if="!scope.row.editDetailDTOS">
                        <span v-if="scope.row.index === clickRow && scope.column.index === clickCell" class="input-index">
                            <el-input
                            ref="editInput"
                            v-model="scope.row.inputList"
                            maxlength="50"
                            size="mini"
                            @blur="inputBlur"
                            />
                        </span>
                        <span v-else>{{ scope.row.inputList }}</span>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="operate" label="操作" width="150px">
                    <template slot-scope="scope">
                        <div class="controller" >
                        <span v-show="scope.row.editDetailDTOS" @click="addChild(scope.$index,scope.row)">
                            <span class="con_div_span">+子属性</span>
                        </span>
                        <span @click="del(scope.$index,scope.row)" v-show="!scope.row.editDetailDTOS&&scope.row.isMe">
                            <span class="con_div_del">删除</span>
                        </span>
                        <span @click="del(scope.$index,scope.row)" v-show="scope.row.editDetailDTOS&&!scope.row.parentFlag">
                            <span class="con_div_span">删除</span>
                        </span>
                        </div>
                    </template>
                </el-table-column>
                </el-table>
                </el-card>
            </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="closeDialog">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
        </span>
        </el-dialog>
    </div>
</template>

<script>
import { getQuery,editcategory,getList } from '@/api/api.js'
  export default {
    props:{
        dialogVisible: {
            type: Boolean,
            default: false
        },
        parentId:{
            type: String,
            default: "-1"
        }
    },
    data() {
      return {
        flag:true, // inputType接收数据时转化
        data_change:"", // 保存name值的修改
        clickRow: null, // 当前点击的行
        clickCell: null, // 当前点击的列
        option:[
            {
                value: 1,
                label: '从属性中获取'
            }, 
            {
                value: 0,
                label: '手工录入'
            }
        ],
        isCheck:false,  // 是否有分类属性
        isAddONE:false,
        centerDialogVisible: this.dialogVisible,
        inputForm:[],
        typeForm:{},
        del_row : []
      };
    },
    watch:{
        async dialogVisible(newVal) {
            this.centerDialogVisible = newVal;
            if(newVal){
               return await this.getQueryById(this.parentId) 
            }   
            
        },
        parentId(id){
            this.typeForm.parentId = id
        },
        inputType(val){
            if (this.flag) {
                this.flag = false
                return val?'从属性中获取':'手工录入'
            }
        }
    },
    methods:{
        // 打开面板时更新已有的数据
        async getQueryById(id) {
            try { 
                const parent_ids = []; // 父id列表
                // 懒加载数据找到父数据
                const parent_id = await(await getList(this.typeForm.catName)).data.result.filter(x=>x.id===id)[0].parentId
                // 获取父数据的内容id
                if (parent_id != -1) {
                    const parent_rs = await (await getQuery(parent_id)).data.result.categoryTypVOList
                    parent_rs.forEach(elem=>{
                        parent_ids.push(elem.id)
                    })
                }

                
                const res = await getQuery(id);  // 获取所需状态值的数据
                
                if (res.data.code == 200) {
                    this.inputForm = res.data.result.categoryTypVOList
                    this.typeForm = res.data.result
                    delete this.typeForm.categoryTypVOList
                    if(this.inputForm.length!=0) {this.isCheck=true;} 

                    let detailDTOS = [];
                    this.inputForm.forEach(element => {
                        if(parent_ids.indexOf(element.id)!==-1){element.parentFlag = true;element.isMe=0}
                        else {element.isMe=1}
                        detailDTOS = [];
                        // console.log(element);
                        detailDTOS = element.categoryAttributeListVOList
                        delete element.categoryAttributeListVOList
                        this.$set(element,'editDetailDTOS',detailDTOS)
                        // element.editDetailDTOS = detailDTOS
                    });
                    this.typeForm.catName = this.typeForm.name
                    delete this.typeForm.name
                    console.log("-=-=-=-=");
                    console.log(this.inputForm);
                }
            } catch (error) {
                console.log(error);
            }
        },
        closeDialog() {
            // 当点击关闭按钮时，更新本地数据并发出事件通知父组件  
            this.centerDialogVisible = false;
            this.inputForm = [];
            this.typeForm.catName = ""
            this.typeForm.memo = ""
            this.typeForm.parentId = -1
            this.isCheck = false
            this.$emit('update', false);
        },
        del(index,row){
            // console.log("index:"+index)
            // console.log(row)
            // console.log(this.inputForm);
            
            let parent_num = 0,children_num=0,tag=0; // parent_num 父循环 tag 子循环次数
            for(let elem of this.inputForm) {
                if (index==elem.index) {
                    if (elem.id){
                        this.$message({
                            message: "不可删除",
                            type: 'fail'
                        });
                        return ;
                    }
                    return this.inputForm.splice(index-children_num,1)
                }
                for(let val of elem.editDetailDTOS){
                    tag++;
                    if (index==val.index) {
                        if (val.attributeTypeId) {
                            row.delFlag = 1;
                            this.del_row.push(val)
                        }
                        // console.log("val:");
                        // console.log(val);
                        return this.inputForm[parent_num].editDetailDTOS.splice(index-(parent_num+1)-(children_num),1); 
                    } 
                }
                children_num+=tag;
                tag = 0
                parent_num++;
                
            }
            
            console.log(this.inputForm);
            this.$message({
                message: "删除成功",
                type: 'success'
            });
        },
        async submit(){
            // console.log(this.del_row);
            // console.log(this.inputForm);
            if(this.isCheck){
                this.del_row.forEach(v=>{
                    for(let e of this.inputForm){
                        if (v.attributeTypeId===e.id) {
                            e.editDetailDTOS.push(v);
                            break;
                        }
                    }
                })
                this.typeForm.editDTOS = this.inputForm
            }
            // console.log(this.typeForm);
            try{
                const res = await editcategory(this.typeForm)
                // console.log(res)
                if(res.data.code == 200){
                    this.$message({
                        message: "编辑成功",
                        type: 'success'
                    });
                    this.$emit('comfirm')
                    this.closeDialog()
                }
            }catch(error){
                console.error("提交失败:", error);
            }
        },
        // 添加一级属性
        addPrimary(){
            this.isAddONE = true
            let obj = {
                    "isMe":1,
                    "editDetailDTOS": [
                    ], 
                    "name": ""
                }
            console.log(this.inputForm);
            this.inputForm.push(obj)
        },
        // 添加二级属性
        addChild(index,row){
            let obj = {
                    "isMe":1,
                    "handAddStatus": 0,
                    "inputList": "",
                    "inputType": "",
                    "name": "",
                    "selectType": 0,
                    "sort": 0
                }
                row.editDetailDTOS.push(obj);
                // this.inputForm[index].editDetailDTOS.push(obj);
            // this.$set(this.inputForm[index].editDetailDTOS,row.editDetailDTOS.length, obj);
            console.log("---");
            console.log(this.inputForm);
        },
        tabClick(row, column, cell, event) {
            this.clickRow = row.index
            this.clickCell = column.index
            this.data_change = row.name
        },
        // 把每一行的索引放进row
        tableRowClassName({ row, rowIndex }) {
            row.index = rowIndex;
        },
    
        // 把每一列的索引放进column
        tableCellClassName({ column, columnIndex }) {
            column.index = columnIndex;
        },
    
        // 失去焦点初始化
        inputBlur(row, event, column) {
            this.clickRow = null;
            this.clickCell = null;
            row.name = this.data_change
        },
        
    },
  };
</script>

<style scoped>
.addPrimary{
    position: absolute;
    top:400px;
    right: 40px;
}
.main-table {
  height: 200px;
  flex:1;/*使内容区域填充剩余空间 */
  overflow-y:auto;/*当内容超出时显示滚动条*/
  scrollbar-width:thin;
}
/* 修改表树形结构 */
.el-table /deep/ .el-icon-arrow-right:before {
  content: ""
}

.name-position {
    display: inline-block;
    transform: translateX(50px);
}

/* //没有子节点 */
.el-tree /deep/.el-tree-node__expand-icon.is-leaf::before
.el-table /deep/.el-table__placeholder::before {
  content: '';
}
.el-table /deep/ .el-switch__core{
    border: 1px solid black;
}

.con_div_span {
    margin: 10px;
}
.con_div_del{
    margin-left: 60px;
}

.custom-checkbox /deep/ .content{
    transform: translateX(-88px);
}
.custom-checkbox /deep/ .content span {
    margin-left: 10px;
}
.el-table  /deep/ .cell .el-select{
    height:18px
}
.input-index {
    display: inline-block;
    width: 100px;
}
.ParentFlag {
    display: inline-block;
    width: 80px;
    background-color: red;
    color: white;
    
}
</style>